<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { axiosrmedical } from '../../http/axiosRead';
import { axioswmedical } from '../../http/axiosWrtie';
import { usePaymentStore } from '@/stores/payment';

const route = useRoute();
const router = useRouter();
const paymentStore = usePaymentStore();

// 定义数据结构接口
interface ItemDetail {
  name: string;
  unitPrice: number;
  quantity: number;
  amount: number;
}

interface PaymentDetail {
  id: number;
  itemName: string;
  departmentName: string;
  doctorName: string;
  patientName: string;
  idCard: string;
  itemDetails: ItemDetail[];
  paymentMethod: string;
  cardBalance: number;
  totalAmount: number;
  isPaid:Boolean;
  orderNo:string;
  createTime:string;
}

interface ResponseData {
  msg: string;
  code: number;
  data: PaymentDetail;
}

// 响应数据
const paymentDetail = ref<PaymentDetail>({
  id: 0,
  itemName: '',
  departmentName: '',
  doctorName: '',
  patientName: '',
  idCard: '',
  itemDetails: [],
  paymentMethod: '余额',
  cardBalance: 0,
  totalAmount: 0,
  isPaid: false,
  orderNo: "REG202507232155144",
  createTime:''
});

// 加载状态
const loading = ref(false);

// 获取缴费详情数据
const fetchPaymentDetail = async () => {
  loading.value = true;
  const paymentId = route.query.paymentId;
  
  if (!paymentId) {
    console.error('缺少缴费项目ID');
    router.back();
    return;
  }
  
  try {
    const response = await axiosrmedical.get('/Payment/GetPaymentDetail', {
      params: {
        paymentId
      }
    });
    const responseData: ResponseData = response.data;
    if (responseData.code === 200) {
      paymentDetail.value = responseData.data;
    }
  } catch (error) {
    console.error('获取缴费详情失败:', error);
    // 添加默认测试数据
    // paymentDetail.value = {
    //   id: Number(paymentId),
    //   itemName: '西药费',
    //   departmentName: '消化内科',
    //   doctorName: '李梅',
    //   patientName: '牛韦',
    //   idCard: '610*********0989',
    //   itemDetails: [
    //     {
    //       name: '普罗布考片',
    //       unitPrice: 50.00,
    //       quantity: 3,
    //       amount: 150.00
    //     },
    //     {
    //       name: '阿司匹林肠溶片',
    //       unitPrice: 50.00,
    //       quantity: 3,
    //       amount: 150.00
    //     }
    //   ],
    //   paymentMethod: '余额',
    //   cardBalance: 2000.00,
    //   totalAmount: 600.00
    // };
  } finally {
    loading.value = false;
  }
};

// 处理缴费支付
const handlePayment = async () => {
  try {
    const response = await axioswmedical.post('/Alipay/WapPay', {
      outTradeNo: paymentDetail.value.orderNo.toString(),
      subject: paymentDetail.value.itemName,
      body: `${paymentDetail.value.patientName}在${paymentDetail.value.departmentName}的缴费`,
      totalAmount: paymentDetail.value.totalAmount.toString(),
      notifyUrl: "http://101.201.170.32:5289/api/AlipayNotify/wappay",
      returnUrl: `${window.location.origin}/payment-success?paymentId=${paymentDetail.value.id}`
    });
    
    // 支付成功后存储 paymentId
    paymentStore.setPaymentId(paymentDetail.value.id.toString());
    
    document.write(response.data);
  } catch (error) {
    console.error('缴费支付失败:', error);
  }
};

// 去充值
const goToRecharge = () => {
  // 跳转到充值页面，带上当前患者 idCard 作为 patientId
  router.push({ path: '/recharge-card', query: { patientId: paymentDetail.value.idCard } });
};

// 格式化金额
const formatAmount = (amount: number) => {
  return amount.toFixed(2);
};

// 页面加载时获取数据
onMounted(() => {
  fetchPaymentDetail();
});
</script>

<template>
  <div class="payment-detail-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar 
      title="确认缴费信息" 
      left-arrow
      @click-left="$router.back()"
    >
      <template #right>
        <van-icon name="ellipsis" size="20" />
        <van-icon name="circle" size="20" class="ml-2" />
      </template>
    </van-nav-bar>

    <div class="content" v-if="!loading">
      <!-- 基本信息卡片 -->
      <div class="info-card">
        <div class="info-item">
          <div class="item-label">费用类型</div>
          <div class="item-value">{{ paymentDetail.itemName }}</div>
        </div>
        <div class="info-item">
          <div class="item-label">就诊科室</div>
          <div class="item-value">{{ paymentDetail.departmentName }}</div>
        </div>
        <div class="info-item">
          <div class="item-label">医生姓名</div>
          <div class="item-value">{{ paymentDetail.doctorName }}</div>
        </div>
        <div class="info-item">
          <div class="item-label">就诊人</div>
          <div class="item-value">{{ paymentDetail.patientName }}</div>
        </div>
        <div class="info-item">
          <div class="item-label">就诊卡号</div>
          <div class="item-value">{{ paymentDetail.idCard }}</div>
        </div>
      </div>

      <!-- 费用明细 -->
      <div class="detail-card">
        <div class="card-title">费用明细</div>
        <div class="fee-items">
          <div class="fee-item" v-for="(item, index) in paymentDetail.itemDetails" :key="index">
            <div class="fee-item-name">{{ item.name }}</div>
            <div class="fee-item-price">
              <div class="price-detail">
                <span class="unit-price">单价: ¥{{ formatAmount(item.unitPrice) }}</span>
                <span class="quantity">数量: {{ item.quantity }}</span>
              </div>
              <div class="amount">¥{{ formatAmount(item.amount) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="payment-method-card">
        <div class="payment-method-title">支付方式</div>
        <div class="payment-method-value">{{ paymentDetail.paymentMethod }}</div>
      </div>
      
      <!-- 卡内余额 -->
      <div class="balance-card">
        <div class="balance-info">
          <div class="balance-label">卡内余额</div>
          <div class="balance-value">{{ paymentDetail.cardBalance.toFixed(2) }}元</div>
        </div>
        <div class="recharge-btn" @click="goToRecharge">
          去充值
          <van-icon name="arrow" />
        </div>
      </div>

      <!-- 底部结算栏 -->
      <div class="payment-footer">
        <div class="total-amount">
          合计: <span class="amount-value">{{ paymentDetail.totalAmount.toFixed(2) }}</span>
        </div>
        <span style="color: cadetblue;">支持通过手机浏览器支付</span>
        <van-button type="primary" class="pay-button" @click="handlePayment">扣款缴费</van-button>
      </div>
    </div>

    <!-- 加载中状态 -->
    <van-loading v-if="loading" class="loading-spinner" />
  </div>
</template>

<style scoped>
.payment-detail-page {
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 20px;
}

.info-card {
  background-color: #ffffff;
  margin-bottom: 10px;
  padding: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.item-label {
  color: #666;
  font-size: 15px;
}

.item-value {
  color: #333;
  font-size: 15px;
}

.detail-card {
  background-color: #ffffff;
  margin-bottom: 10px;
  padding: 16px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}

.fee-items {
  display: flex;
  flex-direction: column;
}

.fee-item {
  border-bottom: 1px solid #f5f5f5;
  padding: 12px 0;
}

.fee-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.fee-item-name {
  font-size: 15px;
  margin-bottom: 8px;
}

.fee-item-price {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.price-detail {
  display: flex;
  flex-direction: column;
}

.unit-price, .quantity {
  font-size: 13px;
  color: #999;
}

.amount {
  font-size: 15px;
  color: #ff4d4f;
  font-weight: 500;
}

.payment-method-card {
  background-color: #ffffff;
  margin-bottom: 10px;
  padding: 16px;
  display: flex;
  justify-content: space-between;
}

.payment-method-title {
  color: #666;
  font-size: 15px;
}

.payment-method-value {
  color: #333;
  font-size: 15px;
}

.balance-card {
  background-color: #ffffff;
  margin-bottom: 10px;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.balance-info {
  display: flex;
  flex-direction: column;
}

.balance-label {
  font-size: 15px;
  color: #666;
  margin-bottom: 4px;
}

.balance-value {
  font-size: 16px;
  font-weight: 500;
}

.recharge-btn {
  color: #1989fa;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.payment-footer {
  background-color: #ffffff;
  margin: 10px 0;
  padding: 16px;
  border-radius: 8px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.total-amount {
  font-size: 14px;
  color: #333;
  display: flex;
  align-items: baseline;
}

.amount-value {
  color: #ff4d4f;
  font-weight: 600;
  font-size: 20px;
  margin-left: 5px;
}

.pay-button {
  width: 160px;
  height: 44px;
  font-size: 16px;
  background-color: #0066ff;
  border: none;
  border-radius: 22px;
}

.loading-spinner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.ml-2 {
  margin-left: 8px;
}
</style> 